import 'package:flutterapp/common/base/base_json_factory.dart';
import 'package:flutterapp/common/util/log_utils.dart';
import 'package:flutterapp/home/entity/home_article_list_entity.dart';
import 'package:flutterapp/home/entity/home_article_top_entity.dart';
import 'package:flutterapp/home/entity/home_banner_entity.dart';
import 'package:flutterapp/item/entity/item_list_entity.dart';
import 'package:flutterapp/item/entity/item_tree_entity.dart';
import 'package:flutterapp/me/entity/collect_article_list_entity.dart';
import 'package:flutterapp/me/entity/login_entity.dart';
import 'package:flutterapp/me/entity/register_entity.dart';
import 'package:flutterapp/system/entity/app_check_entity.dart';
import 'package:flutterapp/system/entity/system_list_by_cid_entity.dart';
import 'package:flutterapp/system/entity/system_tree_entity.dart';

/// 默认的json数据解析工场
class DefaultJsonFactory implements BaseJsonFactory {
  //私有实例
  static DefaultJsonFactory? _instance;
  //单一实例方法，对外提供对象
  static DefaultJsonFactory getInstance() {
    if (_instance == null) _instance = DefaultJsonFactory._();
    return _instance!;
  }

  /// 私有构造器
  DefaultJsonFactory._();

  Type typeOf<T>() => T;

  @override
  T onResponse<T>(data) {
    String tType = typeOf<T>().toString();
    String dataType = data.runtimeType.toString();

    LogUtils.d('传入的数据类型为: $dataType \n 需要返回的数据类型为: $tType');

    // 对不同的数据类型进行处理
    if (dataType.contains('Map<String, dynamic>')) {
      //是否是Map<String, dynamic>
      return fromJson<T>(data);
    } else if (dataType == 'String' && tType == 'String') {
      //是否是String类型
      return data as T;
    } else {
      throw '数据类型不匹配';
    }
  }

  /// 将map转化为T类型的数据对象
  T fromJson<T>(Map<String, dynamic> data) {
    Type type = typeOf<T>();
    switch (type) {
      case dynamic:
        return data as T;
      case HomeBannerEntity:
        return HomeBannerEntity.fromJson(data) as T;
      case LoginEntity:
        return LoginEntity.fromJson(data) as T;
      case RegisterEntity:
        return RegisterEntity.fromJson(data) as T;
      case HomeArticleTopEntity:
        return HomeArticleTopEntity.fromJson(data) as T;
      case HomeArticleListEntity:
        return HomeArticleListEntity.fromJson(data) as T;
      case SystemTreeEntity:
        return SystemTreeEntity.fromJson(data) as T;
      case SystemListByCidEntity:
        return SystemListByCidEntity.fromJson(data) as T;
      case CollectArticleListEntity:
        return CollectArticleListEntity.fromJson(data) as T;
      case AppCheckEntity:
        return AppCheckEntity.fromJson(data) as T;
      case ItemTreeEntity:
        return ItemTreeEntity.fromJson(data) as T;
      case ItemListEntity:
        return ItemListEntity.fromJson(data) as T;
      default:
        throw '没有这样的类型:$type';
    }
  }
}
